package com.heima.wemedia.service.impl;


import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.constants.WemediaConstants;
import com.heima.common.constants.WmNewsMessageConstants;
import com.heima.common.exception.CustomException;
import com.heima.model.wemedia.dtos.NewsAuthDto;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.dtos.ReviewListDto;
import com.heima.model.wemedia.dtos.WmNewsDto;
import com.heima.model.wemedia.dtos.WmNewsPageReqDto;
import com.heima.model.wemedia.pojos.WmMaterial;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.model.wemedia.pojos.WmNewsMaterial;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.wemedia.mapper.WmMaterialMapper;
import com.heima.wemedia.mapper.WmNewsMapper;
import com.heima.wemedia.mapper.WmNewsMaterialMapper;
import com.heima.wemedia.mapper.WmUserMapper;
import com.heima.wemedia.service.WmNewsAutoScanService;
import com.heima.wemedia.service.WmNewsService;
import com.heima.wemedia.service.WmNewsTaskService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PostMapping;
import thread.WmThreadLocalUtil;

import java.util.*;
import java.util.stream.Collectors;

@Service
@Slf4j
@Transactional
public class WmNewsServiceImpl extends ServiceImpl<WmNewsMapper, WmNews> implements WmNewsService {


    /**
     * 加载文章列表
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult findList(WmNewsPageReqDto dto) {

        //1.检查参数
        dto.checkParam();

        //2.条件分页查询

        IPage page = new Page(dto.getPage(), dto.getSize());

        LambdaQueryWrapper<WmNews> lambdaQueryWrapper = new LambdaQueryWrapper();

        //按照文章状态查询
        if (dto.getStatus() != null) {
            lambdaQueryWrapper.eq(WmNews::getStatus, dto.getStatus());
        }

        //按照关键字到title中模糊查询
        if (StringUtils.isNotBlank(dto.getKeyword())) {
            lambdaQueryWrapper.like(WmNews::getTitle, dto.getKeyword());
        }

        //按照频道查询
        if (dto.getChannelId() != null) {
            lambdaQueryWrapper.eq(WmNews::getChannelId, dto.getChannelId());
        }

        //按照时间范围查询
        if (dto.getBeginPubDate() != null && dto.getEndPubDate() != null) {
            lambdaQueryWrapper.between(WmNews::getCreatedTime, dto.getBeginPubDate(), dto.getEndPubDate());
        }

        //按照当前登录人查询
        lambdaQueryWrapper.eq(WmNews::getUserId, WmThreadLocalUtil.getUser().getId());

        //按照时间倒序查询
        lambdaQueryWrapper.orderByDesc(WmNews::getCreatedTime);


        page = page(page, lambdaQueryWrapper);

        //3.结果返回
        ResponseResult responseResult = new PageResponseResult(dto.getPage(), dto.getSize(), (int) page.getTotal());
        responseResult.setData(page.getRecords());


        return responseResult;
    }

    @Autowired
    private WmUserMapper wmUserMapper;

    /**
     * 人工审核查询文章列表
     *
     * @param dto
     * @return
     */
    @Override
    public PageResponseResult findArticleList(NewsAuthDto dto) {

        //1.检查参数
        dto.checkParam();

        //2.条件分页查询
        IPage page = new Page(dto.getPage(), dto.getSize());
        LambdaQueryWrapper<WmNews> lambdaQueryWrapper = new LambdaQueryWrapper<>();

        //按照审核状态查询
        if (dto.getStatus() != null) {
            lambdaQueryWrapper.eq(WmNews::getStatus, dto.getStatus());
        }

        //按照文章标题title模糊查询
        if (StringUtils.isNotBlank(dto.getTitle())) {
            lambdaQueryWrapper.like(WmNews::getTitle, dto.getTitle());
        }

        //按照时间倒叙查询
        lambdaQueryWrapper.orderByDesc(WmNews::getCreatedTime);

        page = page(page, lambdaQueryWrapper);

        //得到分页查询出来的数据
        List<WmNews> records = page.getRecords();
        //为了添加上作者名字新创建的list
        List<ReviewListDto> reviewListDtos = new ArrayList();

        for (WmNews record : records) {
            //获取作者姓名
            Integer userId = record.getUserId();
            WmUser wmUser = wmUserMapper.selectById(userId);
            ReviewListDto reviewListDto = new ReviewListDto();
            if (wmUser != null) {
                reviewListDto.setAuthorName(wmUser.getName());
            }
            //拷贝到带有作者名字的dto类中
            BeanUtils.copyProperties(record, reviewListDto);
            reviewListDtos.add(reviewListDto);
        }

        PageResponseResult pageResponseResult = new PageResponseResult(dto.getPage(), dto.getSize(), (int) page.getTotal());
        pageResponseResult.setData(reviewListDtos);
        return pageResponseResult;
    }

    @Autowired
    private WmNewsMapper wmNewsMapper;

    /**
     * 内容审核之点击获得内容详情
     *
     * @param id
     * @return
     */
    @Override
    public ResponseResult findDetailById(Integer id) {
        if (id == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //获取审核内容详情
        WmNews wmNews = wmNewsMapper.selectById(id);
        ReviewListDto reviewListDto = new ReviewListDto();
        //获取作者姓名
        WmUser wmUser = wmUserMapper.selectById(wmNews.getUserId());
        if (wmUser != null) {
            reviewListDto.setAuthorName(wmUser.getName());
        }
        BeanUtils.copyProperties(wmNews, reviewListDto);

        return ResponseResult.okResult(reviewListDto);
    }

    /**
     * 人工审核之拒绝
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult authFail(NewsAuthDto dto) {
        if (dto == null || dto.getId() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        LambdaUpdateWrapper<WmNews> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(WmNews::getId, dto.getId());
        if (dto.getStatus() != null) {
            updateWrapper.set(WmNews::getStatus, dto.getStatus());
        }
        if (dto.getMsg() != null) {
            updateWrapper.set(WmNews::getReason, dto.getMsg());
        }
        wmNewsMapper.update(null, updateWrapper);

        return new ResponseResult(200, "驳回成功");
    }

    /**
     * 人工审核之通过
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult authPass(NewsAuthDto dto) {
        if (dto == null || dto.getId() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        LambdaUpdateWrapper<WmNews> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(WmNews::getId, dto.getId());
        if (dto.getStatus() != null) {
            updateWrapper.set(WmNews::getStatus, dto.getStatus());
        } else {
            updateWrapper.set(WmNews::getStatus, 4);
        }
        updateWrapper.set(WmNews::getReason, "审核成功");

        wmNewsMapper.update(null, updateWrapper);

        return new ResponseResult(200, "审核通过成功");

    }

    @Autowired
    private WmNewsAutoScanService wmNewsAutoScanService;

    @Autowired
    private WmNewsTaskService wmNewsTaskService;

    /**
     * 发布（草稿、提交待审核）或修改文章
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult submitNews(WmNewsDto dto) {


        //1.检查参数
        if (dto == null || StringUtils.isBlank(dto.getContent())) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        //2.保存或修改文章（是否存在id）
        WmNews wmNews = saveOrUpdateWmNews(dto);

        //3.判断是否是草稿
        if (dto.getStatus().equals(WmNews.Status.NORMAL.getCode())) {
            return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
        }

        //提取文章内容的图片列表
        List<String> materilas = ectractUrlInfo(dto.getContent());

        //4.保存文章内容图片与素材的关系
        saveRelativeInfoForContent(materilas, wmNews.getId());

        //5.保存文章封面图片与素材的关系,如果用户的封面类型选择的是自动，则需要到文章内容中匹配图片作为封面
        saveRelativeInfoForCover(materilas, wmNews, dto);

        //审核文章
        wmNewsAutoScanService.autoScanWmNews(wmNews.getId());
//        wmNewsTaskService.addWmNewsToTask(wmNews);
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /**
     * 1.如果用户的封面类型选择的是自动，则需要到文章内容中匹配图片作为封面
     * `匹配规则：
     * 内容中无图->无图
     * 内容中的图片>=1<3->单图
     * 内容中图片大于等于3->多图`
     * <p>
     * 2.保存文章封面图片与素材的关系
     *
     * @param materilas
     * @param wmNews
     * @param dto
     */
    private void saveRelativeInfoForCover(List<String> materilas, WmNews wmNews, WmNewsDto dto) {

        //获取用户从浏览器输入的封面图片列表
        List<String> images = dto.getImages();

        //用户选择了封面类型为自动，需要自动匹配
        if (dto.getType().equals(WemediaConstants.WM_NEWS_TYPE_AUTO)) {
            int size = materilas.size();
            if (size >= 1 && size < 3) {
                //单图
                images = materilas.stream().limit(1).collect(Collectors.toList());
                //设置图片的封面类型
                wmNews.setType(WemediaConstants.WM_NEWS_SINGLE_IMAGE);
            } else if (size >= 3) {
                //多图
                images = materilas.stream().limit(3).collect(Collectors.toList());
                //设置图片的封面类型
                wmNews.setType(WemediaConstants.WM_NEWS_MANY_IMAGE);
            } else {
                //无图
                //设置图片的封面类型
                wmNews.setType(WemediaConstants.WM_NEWS_NONE_IMAGE);
            }

            //修改文章
            if (images != null && images.size() > 0) {
                wmNews.setImages(StringUtils.join(images, ","));
            }
            updateById(wmNews);
        }

        //保存文章封面图片与素材的关系
        saveRelativeInfo(images, wmNews.getId(), WemediaConstants.WM_COVER_REFERENCE);

    }

    /**
     * 保存文章内容图片与素材的关系
     *
     * @param materilas
     * @param newsId
     */
    private void saveRelativeInfoForContent(List<String> materilas, Integer newsId) {
        saveRelativeInfo(materilas, newsId, WemediaConstants.WM_CONTENT_REFERENCE);
    }

    @Autowired
    private WmMaterialMapper wmMaterialMapper;

    /**
     * 保存文章图片与素材的关系到数据库中
     *
     * @param materilas
     * @param newsId
     * @param type
     */
    private void saveRelativeInfo(List<String> materilas, Integer newsId, Short type) {

        if (materilas != null && materilas.size() > 0) {

            //去重操作
            materilas = materilas.stream().distinct().collect(Collectors.toList());

            //从数据库中查询素材列表
            List<WmMaterial> dbMaterials = wmMaterialMapper.selectList(Wrappers.<WmMaterial>lambdaQuery().in(WmMaterial::getUrl, materilas));
            //判断素材是否失效
            if (dbMaterials == null || dbMaterials.size() == 0 || materilas.size() != dbMaterials.size()) {
                //提示用户素材失效，数据回滚
                //手动抛出异常
                throw new CustomException(AppHttpCodeEnum.MATERIAL_REFERENCE_FAIL);
            }

            //提取素材的id
            List<Integer> idList = dbMaterials.stream().map(WmMaterial::getId).collect(Collectors.toList());

            //文章只有一份，素材有可能会有多份
            wmNewsMaterialMapper.saveRelatives(idList, newsId, type);
        }

    }

    /**
     * 提取文章内容的图片列表
     *
     * @param content
     * @return
     */
    private List<String> ectractUrlInfo(String content) {
        List<String> list = new ArrayList<>();

        //解析数据，并提取图片url
        List<Map> maps = JSON.parseArray(content, Map.class);
        for (Map map : maps) {
            if (map.get("type").equals("image")) {
                list.add((String) map.get("value"));
            }
        }

        return list;
    }

    @Autowired
    private WmNewsMaterialMapper wmNewsMaterialMapper;

    /**
     * 保存或修改文章（是否存在id）
     *
     * @param dto
     */
    private WmNews saveOrUpdateWmNews(WmNewsDto dto) {

        WmNews wmNews = new WmNews();
        //属性拷贝
        BeanUtils.copyProperties(dto, wmNews);
        //处理不能属性拷贝的内容（字段）
        //封面图片列表
        if (dto.getImages() != null && dto.getImages().size() > 0) {
            //让集合中的元素转换为字符串，并且多个以逗号分割
            String imagesStr = StringUtils.join(dto.getImages(), ",");
            wmNews.setImages(imagesStr);
        }
        //用户选择的自动（封面匹配类型），它的值为-1
        if (dto.getType().equals(WemediaConstants.WM_NEWS_TYPE_AUTO)) {
            wmNews.setType(null);
        }
        //填充其他字段
        wmNews.setCreatedTime(new Date());
        wmNews.setUserId(WmThreadLocalUtil.getUser().getId());
        wmNews.setEnable((short) 1);//默认是上架
        wmNews.setSubmitedTime(new Date());


        if (dto.getId() == null) {
            //新增
            save(wmNews);
        } else {

            //删除文章与素材的关系
            wmNewsMaterialMapper.delete(Wrappers.<WmNewsMaterial>lambdaQuery().eq(WmNewsMaterial::getNewsId, dto.getId()));
            //修改
            updateById(wmNews);
        }

        return wmNews;

    }

    @Autowired
    private KafkaTemplate<String, String> kafkaTemplate;

    /**
     * 文章上下架
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult downOrUp(WmNewsDto dto) {
        //1.检验参数
        if (dto.getId() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        //2.查询文章
        WmNews wmNews = getById(dto.getId());
        if (wmNews == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST, "文章不存在");
        }

        //3.是否是已发布
        if (!wmNews.getStatus().equals(WmNews.Status.PUBLISHED.getCode())) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID, "文章没有发布，不能上下架");
        }

        //4.修改文章
        if (dto.getEnable() != null && dto.getEnable() > -1 && dto.getEnable() < 2) {

            /*wmNews.setEnable(dto.getEnable());
            updateById(wmNews);*/

            //update wmnews set enable = ? where id = ?
            update(Wrappers.<WmNews>lambdaUpdate().eq(WmNews::getId, wmNews.getId())
                    .set(WmNews::getEnable, dto.getEnable()));

            if (wmNews.getArticleId() != null) {
                Map<String, Object> map = new HashMap<>();
                map.put("articleId", wmNews.getArticleId());
                map.put("enable", dto.getEnable());
                //发送消息
                kafkaTemplate.send(WmNewsMessageConstants.WM_NEWS_UP_OR_DOWN_TOPIC, JSON.toJSONString(map));
            }

        }

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /**
     * 根据id查询文章
     *
     * @param id
     * @return
     */
    @Override
    public ResponseResult findWmNewsById(Integer id) {
        //1.检查参数
        if (id == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        //2.查询文章
        WmNews wmNews = getById(id);
        if (wmNews == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST, "当前文章不存在");
        }

        //3.结果返回
        return ResponseResult.okResult(wmNews);
    }

    /**
     * 删除文章
     *
     * @param id
     * @return
     */
    @Override
    public ResponseResult delNews(Integer id) {
        //1.检查参数
        if (id == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        //2.查询文章
        WmNews wmNews = getById(id);
        if (wmNews == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST, "当前文章不存在");
        }

        //3.判断文章是否是上架且发布
        if (wmNews.getStatus().equals(WmNews.Status.PUBLISHED.getCode()) && wmNews.getEnable().equals(WemediaConstants.WM_NEWS_ENABLE_UP)) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID, "当前文章已发布，不能删除");
        }

        //4.删除文章与素材的关系
        wmNewsMaterialMapper.delete(Wrappers.<WmNewsMaterial>lambdaQuery().eq(WmNewsMaterial::getNewsId, wmNews.getId()));

        //5.删除文章
        removeById(wmNews.getId());
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }


}
